import { createSlice } from "@reduxjs/toolkit";

const tabsSlice  = createSlice({
    name:'tabs',
    initialState:()=>{
        if(sessionStorage.getItem("tabsStore")!==null){
            return JSON.parse(sessionStorage.getItem('tabsStore'))
        }
        return {
            tabsList:[{
                key:'/dashboard/console',
                label:'功能功能A1',
                closable: false
            }],
            activeKey:'/dashboard/console'
        }
    },
    reducers:{
        addTab:(state,{payload})=>{
            //遍历数组是否有重复的
            let isRepeat = state.tabsList.some(item=>item.key===payload.key)
            if(isRepeat){
               state.activeKey = payload.key
                return
            }
            state.tabsList.push(payload)
            state.activeKey = payload.key
            sessionStorage.setItem("tabsStore",JSON.stringify(state))
        },
        toggleTab:(state,{payload})=>{
            state.activeKey = payload
            sessionStorage.setItem("tabsStore",JSON.stringify(state))
        },
        removeTab:(state,{payload})=>{
        let index =  state.tabsList.findIndex(item=>item.key === payload)
        state.tabsList.splice(index,1)
        //删除最后一项的时候
        if(index === state.tabsList.length && payload===state.activeKey){
            state.activeKey = state.tabsList[index-1].key
        }
        //高亮的页面时候
        if(state.activeKey === payload){
            state.activeKey = state.tabsList[index].key
        }
        sessionStorage.setItem("tabsStore",JSON.stringify(state))
         
    }
    }
})
export const {addTab,toggleTab,removeTab} = tabsSlice.actions
export default tabsSlice.reducer